package main

import (
	"fmt"
	"time"
)

func main() {
	timeFormat()
	timeSpend()

}

func timeFormat() {
	now := time.Now()
	fmt.Println(now.Format("Mon, Jan 2, 2006 at 3:04pm"))
	fmt.Println("Year: ", now.Year())
	fmt.Println("Month: ", now.Month())
	fmt.Println(now.Format(time.RFC850))
	fmt.Println(now.Format(time.RFC1123))
	est, _ := time.LoadLocation("EST")
	july4 := time.Date(1776, 7, 4, 12, 15, 0, 0, est)
	fmt.Println(july4)

	input_format := "1/2/2006 3:04pm"
	user_str := "4/16/2014 11:38am"
	user_date, err := time.Parse(input_format, user_str)
	if err != nil {
		fmt.Println(">>> Error parsing date string")
	}
	fmt.Println("User date =  ", user_date.Format("Jan 2, 2006 @ 3:04pm"))

	diff := now.Sub(july4)
	fmt.Println(diff)
	fmt.Printf("July 4 was about %d hours ago \n", diff.Hours())

	twodaysDiff := time.Hour * 24 * 2
	twodays := now.Add(twodaysDiff)
	fmt.Println("Two Days: ", twodays.Format(time.ANSIC))

	// 涉及到时区问题，不严谨
	t, _ := time.Parse("2006-01-02 15:04:05", "2016-06-13 09:14:00")
	fmt.Println(time.Now().Sub(t).Hours())
	// 严谨 Time.Location() 函数知道是哪个时区
	t2, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 09:14:00", time.Local)
	fmt.Println(time.Now().Sub(t2).Hours())
	// 获取当前时间整点的 Time 实例。例如，当前时间是15:54:23，需要的是 15:00:00
	t3, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:00:00"), time.Local)
	fmt.Println(t3)

	t4, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local)
	// 整点（向下取整）
	fmt.Println(t4.Truncate(1 * time.Hour))
	// 整点（最接近）
	fmt.Println(t4.Round(1 * time.Hour))
	// 整分（向下取整）
	fmt.Println(t4.Truncate(1 * time.Minute))
	// 整分（最接近）
	fmt.Println(t4.Round(1 * time.Minute))
	t5, _ := time.ParseInLocation("2006-01-02 15:04:05", t.Format("2006-01-02 15:00:00"),
		time.Local)
	fmt.Println(t5)
}

/**
时间花费，时间差
*/
func timeSpend() {
	// 获取当前时间
	start := time.Now()

	// 模拟一些操作
	time.Sleep(2 * time.Second)

	// 获取当前时间
	end := time.Now()

	// 计算时间差
	duration := end.Sub(start)

	// 打印时间差
	fmt.Println("Time Difference:", duration)
}
